package com.virus.server.utils;

import com.virus.server.catalina.Context;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebXmlUtils {

    private static Map<String, String> mimeMap = new HashMap<>();

    static {
        initMineMap();
    }

    public static List<String> parseWelcomeFile() {
        List<String> welcomeFileList = new ArrayList<>();
        try {
            String webXml = FileUtils.readUTF8(Constant.webXml);
            Document document = Jsoup.parse(webXml);
            Elements elements = document.select("welcome-file-list welcome-file");
            for (Element element : elements) {
                String text = element.text();
                welcomeFileList.add(text);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return welcomeFileList;
    }

    public static String getWelcomeFile(Context context) {
        List<String> welcomeFileList = parseWelcomeFile();
        String docBose = context.getDocBose();
        for (String welcomeFile : welcomeFileList) {
            String path = docBose + "/" + welcomeFile;
            File file = new File(path);
            if (file.exists()) {
                return path;
            }
        }
        return "index.jsp";
    }

    public static void initMineMap() {
        try {
            String webXml = FileUtils.readUTF8(Constant.webXml);
            Document document = Jsoup.parse(webXml);
            Elements elements = document.select("mime-mapping");
            for (Element element : elements) {
                String extension = element.select("extension").first().text();
                String mineType = element.select("mime-type").first().text();
                mimeMap.put(extension, mineType);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getMineType(String extension) {
        String mineType = mimeMap.get(extension);
        if (mineType == null) {
            return "text/html";
        }
        return mineType;
    }
}
